package com.wcc.mpmultidb.controller;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.wcc.mpmultidb.common.BizException;
import com.wcc.mpmultidb.common.CommonResult;
import com.wcc.mpmultidb.entity.User;
import com.wcc.mpmultidb.entity.UserPg;
import com.wcc.mpmultidb.service.MasterUserService;
import com.wcc.mpmultidb.service.SlaveUserService;
import com.wcc.mpmultidb.service.TranService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author wuch
 * @version 1.0
 * @date 2021/4/9 9:39
 */
@RestController
@RequestMapping("user")
@Api(tags = "用户服务",description = "用户相关服务")
@CrossOrigin
public class UserController {

    @Autowired
    private MasterUserService masterUserService;

    @Autowired
    private SlaveUserService slaveUserService;

    @Autowired
    private TranService tranService;

    /**
     * 获取用户根据id
     * @return
     */
    @ApiOperation(value = "获取用户根据id", notes = "查询用户")
    @GetMapping("getUserById")
    public CommonResult<User> getUserById(String id){
        User user = masterUserService.getById(id);
        return CommonResult.success(user);
    }

    /**
     * 添加用户
     * @return
     */
    @ApiOperation(value = "添加用户", notes = "从库添加用户")
    @PostMapping("add")
//    @DSTransactional
    public CommonResult<Boolean> addUser(@RequestBody User user){
        try {
            if (user.getCreateTime() == null){
                user.setCreateTime(new Date());
                user.setUpdateTime(new Date());
            }
            UserPg userPg = new UserPg();
            BeanUtils.copyProperties(user,userPg);
            boolean save = slaveUserService.save(userPg);
            masterUserService.save(user);
            int i = 1/0;
            return CommonResult.success(save);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("添加失败", e);
        }
    }

    /**
     * 添加用户
     * @return
     */
    @ApiOperation(value = "添加用户", notes = "测试spring事务注解是否生效")
    @PostMapping("addSpring")
    @DSTransactional
    public CommonResult<Boolean> addUserSpring(@RequestBody User user){
        try {
            if (user.getCreateTime() == null){
                user.setCreateTime(new Date());
                user.setUpdateTime(new Date());
            }
            tranService.tranSave(user);
//            int i = 1/0;
            System.out.println("addUserSpring执行完毕");
            return CommonResult.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("添加失败", e);
        }
    }
}
